//
//  MenuView.m
//  ZFMenuTableView
//
//  Created by 张锋 on 16/7/13.
//  Copyright © 2016年 张锋. All rights reserved.
//

/*
 *  推荐使用方法：将这个View设置为tableView的第一次组的组头视图
 *  目前这个demo只能实现一组下拉列表的情况，多分组的情况以后我会继续增加和优化
 */

#import "MenuListView.h"
#import "MenuButton.h"
#import "UIView+ZF.h"
#import "PBSearchOneCell.h"
#import "PBSearchPriceCell.h"
#import "ZYCalendarView.h"
#import "PBPositionCell.h"

#define kS_W [UIScreen mainScreen].bounds.size.width
#define kS_H [UIScreen mainScreen].bounds.size.height

static NSString * const kPBSearchOneCell = @"PBSearchOneCell";
static NSString * const kPBSearchPriceCell = @"PBSearchPriceCell";
static NSString * const kPBPositionCell = @"PBPositionCell";

#define kAniDuration 0.3f
//#define kTitleCor [UIColor colorWithRed:0.100 green:0.700 blue:0.610 alpha:1.000]

@interface ListCell ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *imgView;

@end

@implementation ListCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *cellId = @"ListCell";
    ListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    [self.contentView addSubview:self.imgView];
    [self.contentView addSubview:self.titleLabel];
}

- (void)setTitle:(NSString *)title
{
    _title = title;
    _titleLabel.text = title;
}

- (void)setIsSelected:(BOOL)isSelected
{
    if (isSelected) {
        [self setSelected:YES animated:YES];
    }else {
        [self setSelected:NO animated:YES];
    }
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        CGFloat titleLabelH = self.h - 2*10.f;
        _titleLabel.frame = CGRectMake(30.f, 10.f, self.w - 100.f, titleLabelH);
        _titleLabel.font = [UIFont systemFontOfSize:14.f];
    }
    return _titleLabel;
}

- (UIImageView *)imgView
{
    if (!_imgView) {
        _imgView = [[UIImageView alloc] init];
        CGFloat imgViewWH = self.h - 2*10.f;
        _imgView.contentMode = UIViewContentModeCenter;
        _imgView.frame = CGRectMake(15.f, 10.f, imgViewWH, imgViewWH);
    }
    return _imgView;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    if (selected) {
        self.titleLabel.textColor = [UIColor tm_mainColor];
        self.imgView.image = [UIImage imageNamed:@"gc_navi_selected_icon"];
        // NSLog(@"选中了");
    }else {
        self.titleLabel.textColor = [UIColor blackColor];
        self.imgView.image = nil;
        // NSLog(@"没选中");
    }
}

@end


#define kLineW 0.5f
#define kLineH 25.f
#define kLineCor [UIColor colorWithWhite:0.850 alpha:1.000]

#define kRowH 50.f

@interface MenuListView () <UITableViewDelegate, UITableViewDataSource,PBSearchOneCellDelegate,PBPositionCellDelegate>
{
    NSString *_currenTitle;
    MenuButton *_button;
}
@property (nonatomic, strong) UITableView *lTableView;
@property (nonatomic, strong) UIView *shadow;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *weekView;
@property (nonatomic, strong) ZYCalendarView *calendarView;
@property (nonatomic, assign) BOOL reset;
@property (nonatomic, strong) ZYCalendarManager *selectManager;
@property (nonatomic, strong) PBSearchPriceCell *cell;
@property (nonatomic, strong) NSMutableDictionary *typeDic;
@property (nonatomic, strong) NSMutableArray    *typeArray; // 几居室
@end

@implementation MenuListView

- (instancetype)initWithFrame:(CGRect)frame Titles:(NSArray<NSString *> *)titles defImage:(UIImage *)defImage selImage:(UIImage *)selImage
{
    self = [super initWithFrame:frame];
    if (self) {
        [self subViewsWithTitles:titles defImage:defImage selImage:selImage];
    }
    return self;
}

- (void)subViewsWithTitles:(NSArray *)titles defImage:(UIImage *)defImage selImage:(UIImage *)selImage
{
    [self.lTableView registerNib:[UINib nibWithNibName:kPBSearchOneCell bundle:nil] forCellReuseIdentifier:kPBSearchOneCell];
    [self.lTableView registerNib:[UINib nibWithNibName:kPBSearchPriceCell bundle:nil] forCellReuseIdentifier:kPBSearchPriceCell];
    [self.lTableView registerNib:[UINib nibWithNibName:kPBPositionCell bundle:nil] forCellReuseIdentifier:kPBPositionCell];
    self.backgroundColor = [UIColor whiteColor];
    // 下边的分割线
    CGRect bottomLineFrame = CGRectMake(0, self.h-1.f, kS_W, 0.5f);
    UIView *bottomLine = [[UIView alloc] initWithFrame:bottomLineFrame];
    bottomLine.backgroundColor = kLineCor;
    [self addSubview:bottomLine];
    
    NSInteger count = [titles count];
    for (int i=0; i<count; i++) {
        // 创建按钮
        CGFloat buttonW = (self.w - (count-1)*kLineW)/count;
        CGFloat buttonH = 40.f;
        CGFloat buttonX = (buttonW+kLineW) * i;
        CGRect btnFrame = CGRectMake(buttonX, 0.f, buttonW, buttonH);
        MenuButton *button = [[MenuButton alloc] initWithFrame:btnFrame title:titles[i] defImage:defImage selImage:selImage];
        [self addSubview:button];
        
        __weak typeof(self)weakSelf = self;
        button.clickMenuButton = ^(MenuButton *button, NSString *title, BOOL selected){
            
            self.count = i;

            if (weakSelf.clickMenuButton) {
                weakSelf.clickMenuButton( button,i, selected);
            }

            if (!_button) {
                _button = button;
            }
            if (button != _button) {
                [_button resetStatus:_button];
            }
            else {
            }
            _currenTitle = title;
            _button = button;
            
            if (selected) {
                if (i == 2) {
                    [self showCalendarViewAnimation];
                }else if (i == 1) {
                    [self showPositonAnimation];
                }else {
                    [self showListViewAnimation];
                }
            }
            else {
                
                [self hideListViewAnimation];
                
            }
            
        };
        
        // 按钮之间的竖直分割线
        if (i < count-1) {
            CGFloat lineX = buttonX + buttonW;
            CGFloat lineY = (self.h-kLineH)/2;
            CGRect lineFrame = CGRectMake(lineX, lineY, kLineW, kLineH);
            UIView *line = [[UIView alloc] initWithFrame:lineFrame];
            line.backgroundColor = kLineCor;
            [self addSubview:line];
        }
    }
}
- (UIView *)weekView {
    if (!_weekView) {
        NSInteger Y;
        if (IS_IPHONE_X) {
            Y = 64+40+22;
        }else {
            Y = 64+40;
        }
        _weekView = [[UIView alloc] initWithFrame:CGRectMake(0, Y, kScreenWidth, 50)];
        _weekView.backgroundColor = [UIColor whiteColor];
        CGFloat weekW = self.frame.size.width/7;
        NSArray *titles = @[@"日", @"一", @"二", @"三",
                            @"四", @"五", @"六"];
        for (int i = 0; i < 7; i++) {
            UILabel *week = [[UILabel alloc] initWithFrame:CGRectMake(i*weekW, 0, weekW, 50)];
            week.textAlignment = NSTextAlignmentCenter;
            week.textColor = [UIColor tm_majorFontColor];
            week.font = [UIFont systemFontOfSize:13];
            [_weekView addSubview:week];
            week.text = titles[i];
        }
    }
    return _weekView;
}
- (ZYCalendarView *)calendarView {
    if (!_calendarView) {
        NSInteger Y;
        if (IS_IPHONE_X) {
            Y = 64+40+22+50;
        }else {
            Y = 64+40+50;
        }
        _calendarView = [[ZYCalendarView alloc] initWithFrame:CGRectMake(0, Y, kScreenWidth, kScreenHeight-Y-60)];
        _calendarView.backgroundColor = [UIColor whiteColor];
        // 不可以点击已经过去的日期
        _calendarView.manager.canSelectPastDays = false;
        // 可以选择时间段
        _calendarView.manager.selectionType = ZYCalendarSelectionTypeSingle;
        // 设置颜色
        _calendarView.manager.defaultTextColor = [UIColor tm_majorFontColor];
        _calendarView.manager.disableTextColor = [UIColor tm_secFontColor];
        _calendarView.manager.selectedBackgroundColor = UIColorWithRGB(243,159,13);
        // 设置当前日期 请在所有参数设置完之后设置日期
        _calendarView.date = [NSDate date];
        kWeakSelf(weakSelf)
        _calendarView.dayViewBlock = ^(ZYCalendarManager *manager, NSDate *dayDate) {
            weakSelf.selectManager = manager;
        };
    }
    return _calendarView;
}

- (UIView *)shadow
{
    if (!_shadow) {
        NSInteger Y;
        if (IS_IPHONE_X) {
            Y = 104+22;
        }else {
            Y = 104;
        }
        _shadow = [[UIView alloc] init];
        _shadow.alpha = 0.f;
        _shadow.userInteractionEnabled = YES;
        _shadow.frame = CGRectMake(0, Y, kS_W, kS_H);
        _shadow.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.6];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shadowViewClick)];
        [_shadow addGestureRecognizer:tap];
    }
    return _shadow;
}

- (UITableView *)lTableView
{
    if (!_lTableView) {
        NSInteger Y;
        if (IS_IPHONE_X) {
            Y = 64+40+22;
        }else {
            Y = 64+40;
        }
        CGRect frame = CGRectMake(0.f, Y, self.w, kScreenHeight-Y-60);
        _lTableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        _lTableView.delegate = self;
        _lTableView.dataSource = self;
        _lTableView.tableFooterView = [[UIView alloc] init];
    }
    return _lTableView;
}
- (UIView *)bottomView
{
    if (!_bottomView) {
        CGRect frame = CGRectMake(0.f, kScreenHeight-60, self.w, 60);
        _bottomView = [[UIView alloc] initWithFrame:frame];
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        UIButton *resetButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
        [resetButton setTitle:@"重置" forState:UIControlStateNormal];
        [resetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        resetButton.backgroundColor = [UIColor lightGrayColor];
        resetButton.titleLabel.font = [UIFont systemFontOfSize:13];
        resetButton.layer.cornerRadius = 3;
        resetButton.layer.masksToBounds = YES;
        [resetButton addTarget:self action:@selector(resetButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:resetButton];
        
        UIButton *sureButton = [[UIButton alloc] initWithFrame:CGRectMake(120, 10, kScreenWidth-130, 40)];
        [sureButton setTitle:@"确定" forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        sureButton.backgroundColor = UIColorWithRGB(243,159,13);
        sureButton.titleLabel.font = [UIFont systemFontOfSize:13];
        sureButton.layer.cornerRadius = 3;
        sureButton.layer.masksToBounds = YES;
        [sureButton addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:sureButton];
        
    }
    return _bottomView;
}

- (void)resetButtonClick {
    if (self.count == 0) {
        self.reset = YES;
        [self.typeDic removeAllObjects];
        [self.lTableView reloadData];
    }else if (self.count == 2) {
        [self.calendarView.manager.selectedDateArray removeAllObjects];
        self.calendarView.date = [NSDate date];
    }else if (self.count == 3) {
        [self.lTableView reloadData];
    }
}

- (void)sureButtonClick {
    if (self.count == 0) {
        if (self.typeDic.count == 0) {
            [self showHint:@"请先选择搜索条件"];
            return;
        }
        
        // 合租/整租
        [self hideListViewAnimation];
        if (self.clickTheValue) {
            self.clickTheValue(self.typeDic);
            [self.typeDic removeAllObjects];
            [self.typeArray removeAllObjects];
        }
    }else if (self.count == 2) {
        // 入住日期
        if (self.selectManager.selectedDateArray.count == 0) {
            [self showHint:@"请选择入住日期"];
            return;
        }
        [self hideListViewAnimation];
        for (NSDate *date in self.selectManager.selectedDateArray) {
            NSLog(@"select = %@", [self.selectManager.dateFormatter stringFromDate:date]);
            if (self.clickTheValue) {
                self.clickTheValue(@{@"enterTime":[self.selectManager.dateFormatter stringFromDate:date]});
            }
        }
    }else if (self.count == 3) {
        // 价格筛选
        [self hideListViewAnimation];
        NSLog(@"%.f",self.cell.slider.currentMinValue);
        NSLog(@"%.f",self.cell.slider.currentMaxValue);
        if (self.clickTheValue) {
            self.clickTheValue(@{@"rentStart":[NSString stringWithFormat:@"%.f",self.cell.slider.currentMinValue],
                                 @"rentEnd":[NSString stringWithFormat:@"%.f",self.cell.slider.currentMaxValue]});
        }
    }
    
}

#pragma mark - 点击背景
- (void)shadowViewClick
{
    [self hideListViewAnimation];
}

// 显示下拉列表
- (void)showListViewAnimation
{
    UIView *superView = self.superview;
    [superView.window addSubview:self.shadow];
    [superView.window addSubview:self.lTableView];
    [superView.window addSubview:self.bottomView];
    self.lTableView.h = kScreenHeight-64-40-60;
//    CGFloat height = [self maxListHeightWithModel:self.dataSource];
    
//    CGFloat height = kScreenHeight-64-40-60;
    
//    [UIView animateWithDuration:kAniDuration animations:^{
        self.shadow.alpha = 1.f;
//        self.lTableView.h = height;
//        self.bottomView.y = kScreenHeight-60;
//        self.bottomView.h = 60;
//    }];
}

- (void)showCalendarViewAnimation {
    UIView *superView = self.superview;
    [superView.window addSubview:self.shadow];
    [superView.window addSubview:self.weekView];
    [superView.window addSubview:self.calendarView];
    [superView.window addSubview:self.bottomView];
    
//    [UIView animateWithDuration:kAniDuration animations:^{
        self.shadow.alpha = 1.f;
//        self.weekView.h = 50;
//        self.calendarView.h = kScreenHeight-64-40-50-60;
//        self.calendarView.y = 64 + 40 + 50;
//        self.bottomView.y = kScreenHeight-60;
//        self.bottomView.h = 60;
//    }];
}

- (void)showPositonAnimation
{
    UIView *superView = self.superview;
    [superView.window addSubview:self.shadow];
    [superView.window addSubview:self.lTableView];
    self.lTableView.h = kScreenHeight-64-40;
}


// 隐藏下拉列表
- (void)hideListViewAnimation
{
//    [UIView animateWithDuration:kAniDuration animations:^{
        self.shadow.alpha = 0.f;
        self.lTableView.h = 0.f;
//        self.bottomView.h = 0.f;
//        self.weekView.h = 0.f;
//        self.calendarView.h = 0.f;
//        self.calendarView.y = 64+40;
//        self.bottomView.y = 64+40;
//    } completion:^(BOOL finished) {
        [self.shadow removeFromSuperview];
        [self.lTableView removeFromSuperview];
        [self.weekView removeFromSuperview];
        [self.calendarView removeFromSuperview];
        [self.bottomView removeFromSuperview];
        [_button resetStatus:_button];
//    }];
}

// 一定要重写这个方法，在这里`reloadData`
- (void)setDataSource:(NSArray *)dataSource
{
    _dataSource = dataSource;
    [self.lTableView reloadData];
}

// 更具数据源里边数据情况，返回TableView高度
- (CGFloat)maxListHeightWithModel:(NSArray *)dataSource
{
    NSInteger count = dataSource.count;
    CGFloat height = 0.f;
    CGFloat oriHeight = kRowH*count;
    oriHeight > kS_H/3*2 ? (height = kS_H/3*2) : (height = kRowH*count);
    
    return height;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.count == 0) {
        return 2;
    }else if (self.count == 3) {
        return 1;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.count == 0) {
        return 160;
    }else if (self.count == 3) {
        return 120;
    }
    return 300;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.lTableView.scrollEnabled = YES;
    if (self.count == 0) {
        PBSearchOneCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBSearchOneCell forIndexPath:indexPath];
        cell.delegate = self;
        [cell refreshWithIndexPath:indexPath reset:self.reset];
        return cell;
    }else if (self.count == 3) {
        PBSearchPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBSearchPriceCell forIndexPath:indexPath];
        [cell refreshWithMinPrice:500 MaxPrice:6000 reset:self.reset];
        self.cell = cell;
        return cell;
    }
    
    PBPositionCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBPositionCell forIndexPath:indexPath];
    self.lTableView.scrollEnabled = NO;
    cell.delegate = self;
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.count != 1) {
        return;
    }
    
//    [UIView animateWithDuration:0.2f animations:^{
        self.shadow.alpha = 0.f;
//        self.lTableView.h = 0.f;
//        self.bottomView.h = 0.f;
//        self.bottomView.y = 64+40;
//    } completion:^(BOOL finished) {
        [self.shadow removeFromSuperview];
        [self.lTableView removeFromSuperview];
        [self.bottomView removeFromSuperview];
        [self.calendarView removeFromSuperview];
        [self.weekView removeFromSuperview];
//    }];
    
    _button.isSeled = NO;
    _button.title = self.dataSource[indexPath.row];
    
    [_button resetStatus:_button];
    
    // 实现回调方法
    if (self.clickListView) {
        self.clickListView(indexPath.row, self.dataSource[indexPath.row],self.count);
    }
}


#pragma mark - PBPositionCellDelegate
- (void)fujinButtonClick {
    [self hideListViewAnimation];
//    _button.isSeled = NO;
//
//    [_button resetStatus:_button];
    
    // 实现回调方法
    if (self.clickTheValue) {
        self.clickTheValue(@{@"findRound":@"false"});
    }
}
- (void)resetPositionButtonClick {
    [self hideListViewAnimation];
    if (self.clickTheValue) {
        self.clickTheValue(@{});
    }
}

- (void)zeroButtonClickWithId:(NSString *)zeroId {
    NSLog(@"zeroId = %@",zeroId);
    [self hideListViewAnimation];
    // 实现回调方法
    if (self.clickTheValue) {
        self.clickTheValue(@{@"countyId":zeroId});
    }
}

- (void)trainButtonClickWithId:(NSString *)trainId {
    NSLog(@"trainId = %@",trainId);
    [self hideListViewAnimation];
    // 实现回调方法
    if (self.clickTheValue) {
        self.clickTheValue(@{@"route":trainId});
    }
}

#pragma mark - PBSearchOneCellDelegate
- (void)chooseTheType:(NSString *)type row:(NSInteger)row{
    
    self.reset = YES;
    if (row == 0) {
        // 合租
        [self.typeDic setValue:@"false" forKey:@"entireRent"];
        [self.lTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }else {
        // 整租
        [self.typeDic setValue:@"true" forKey:@"entireRent"];
        [self.lTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
    
    
    if ([type isEqualToString:@"不限"]) {
        [self.typeDic removeObjectForKey:@"roomNumList"];
    }else if ([type isEqualToString:@"1居"]) {
        [self.typeArray addObject:@"1"];
        [self.typeDic setValue:self.typeArray forKey:@"roomNumList"];
    }else if ([type isEqualToString:@"2居"]) {
        [self.typeArray addObject:@"2"];
        [self.typeDic setValue:self.typeArray forKey:@"roomNumList"];
    }else if ([type isEqualToString:@"3居"]) {
        [self.typeArray addObject:@"3"];
        [self.typeDic setValue:self.typeArray forKey:@"roomNumList"];
    }
    
}
- (void)cancleTheType:(NSString *)type row:(NSInteger)row{
    
    if ([type isEqualToString:@"不限"]) {
        [self.typeDic removeObjectForKey:@"roomNumList"];
    }else if ([type isEqualToString:@"1居"]) {
        [self.typeArray removeObject:@"1"];
        [self.typeDic setValue:self.typeArray forKey:@"roomNumList"];
    }else if ([type isEqualToString:@"2居"]) {
        [self.typeArray removeObject:@"2"];
        [self.typeDic setValue:self.typeArray forKey:@"roomNumList"];
    }else if ([type isEqualToString:@"3居"]) {
        [self.typeArray removeObject:@"3"];
        [self.typeDic setValue:self.typeArray forKey:@"roomNumList"];
    }
    
}

- (NSMutableDictionary *)typeDic {
    if (!_typeDic) {
        _typeDic = [[NSMutableDictionary alloc] init];
    }
    return _typeDic;
}
- (NSMutableArray *)typeArray {
    if (!_typeArray) {
        _typeArray = [[NSMutableArray alloc] init];
    }
    return _typeArray;
}



@end
